﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Permissions;
using System.Web;
using mijiaxueche.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace mijiaxueche.weixin.help
{
    public class GetUserinfo
    {
        public static string GetOpenid(string code)
        {
            string url =
                string.Format(
                    "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                    wxHelper.appid, wxHelper.secret, code);
            string json = GetTextByUrl.GetGZipEncodedHTMLContent(url, "");

            //json=" \"access_token\":\"ACCESS_TOKEN\",
            // "expires_in":7200,
            // "refresh_token":"REFRESH_TOKEN",
            //string json = "\"openid\":\"OPENID\"";
            //"scope":"SCOPE""
            string openid = json.Substring(json.IndexOf("openid\":\"") + 9)
                .Substring(0, json.Substring(json.IndexOf("openid\":\"") + 9).IndexOf('"'));
            return openid;
        }

        public static wxUserInfo getWxUserInfo(string code)
        {
            try
            {
                wxUserInfo model = new wxUserInfo();
                string url =
                    string.Format(
                        "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
                        wxHelper.appid, wxHelper.secret, code);
                string json = GetTextByUrl.GetGZipEncodedHTMLContent(url, "");
                Logger.Info("获取用户信息 json:" + json);

                if (!json.Contains("errcode"))
                {
                    JObject ja = (JObject)JsonConvert.DeserializeObject(json);
                    string access_token = ja["access_token"].ToString();
                    string openid = ja["openid"].ToString();
                    string urlinfo =
                        string.Format(" https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN",
                            access_token, openid);
                    //string urlinfo =
                    //   string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN",
                    //       access_token, openid);

                    string info = GetTextByUrl.GetGZipEncodedHTMLContent(urlinfo, "UTF-8");
                    Logger.Info("获取用户信息 info:" + info);
                    if (!json.Contains("errcode"))
                    {
                        JObject jafo = (JObject)JsonConvert.DeserializeObject(info);
                        if (jafo != null)
                        {
                            model.openid = openid;
                            model.nickname = jafo["nickname"].ToString();
                            model.sex = jafo["sex"].ToString();
                            model.language = jafo["language"].ToString();
                            model.city = jafo["city"].ToString();
                            model.province = jafo["province"].ToString();
                            model.country = jafo["country"].ToString();
                            model.headimgurl = jafo["headimgurl"].ToString();
                            model.privilege = jafo["privilege"].ToString();
                        }
                    }
                }
                return model;
            }
            catch (Exception e)
            {
                Logger.Error("获取微信用户基本信息失败", e);
                return null;
            }
        }

        /// <summary>
        /// 获取单个教练的信息
        /// </summary>
        /// <param name="strId"></param>
        /// <returns></returns>
        public static string getTeacherInfo(string strId)
        {
            return GetTextByUrl.getDataFromUrl(String.Format("{0}/wxapi/Teacher/getTeacherOne?teaid={1}", ConfigurationManager.AppSettings["apiUri"], strId));
        }

        /// <summary>
        /// 获取单个驾校的信息
        /// </summary>
        /// <param name="strId"></param>
        /// <returns></returns>
        public static string getSchoolInfo(string strId)
        {
            return GetTextByUrl.getDataFromUrl(String.Format("{0}/wxapi/School/getSchoolOne?schid={1}", ConfigurationManager.AppSettings["apiUri"], strId));
        }
    }

    /// <summary>
    /// 微信用户信息对象
    /// </summary>
    public class wxUserInfo
    {
        /// <summary>
        /// wx唯一标识
        /// </summary>
        public string openid { get; set; }

        /// <summary>
        /// 用户昵称
        /// </summary>
        public string nickname { get; set; }

        /// <summary>
        /// 性别（值）
        /// </summary>
        public string sex { get; set; }

        /// <summary>
        /// 性别（名称）
        /// </summary>
        public string sexName
        {
            get
            {
                switch (sex)
                {
                    case "1":
                        return "男";
                        break;
                    case "2":
                        return "女";
                        break;
                    default:
                        return "未知";
                }
            }
        }

        /// <summary>
        /// 语言
        /// </summary>
        public string language { get; set; }

        /// <summary>
        /// 所在城市
        /// </summary>
        public string city { get; set; }

        /// <summary>
        /// 所在省份
        /// </summary>
        public string province { get; set; }

        /// <summary>
        /// 所在国家
        /// </summary>
        public string country { get; set; }

        /// <summary>
        /// 头像
        /// </summary>
        public string headimgurl { get; set; }

        /// <summary>
        /// 分组
        /// </summary>
        public string privilege { get; set; }
    }
}